//
//  WCImgBrowserView.m
//  WCN
//
//  Created by 杨鑫 on 15/6/4.
//  Copyright (c) 2015年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCImgBrowserView.h"
#import "WCNImageCCell.h"
//
#import "WCPopupLayerManager.h"
//
#import "NSObject+Utilities.h"

static NSString *cellId = @"WCNImageCCell";

@interface WCImgBrowserView () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (weak, nonatomic) UICollectionView *collectionView;
@property (weak, nonatomic) UIPageControl *pageControl;

@property (nonatomic) BOOL firstShow;

@end

@implementation WCImgBrowserView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor blackColor];
        
        _firstShow = YES;
        
        [self loadiew];
        
        UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeBrowser:)];
        [self addGestureRecognizer:tapRecognizer];
    }
    return self;
}

- (void)loadiew
{
    //init UICollectionViewFlowLayout
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.itemSize = CGSizeMake(self.bounds.size.width, self.bounds.size.height);
    //init UICollectionView
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:flowLayout];
    collectionView.dataSource = self;
    collectionView.delegate = self;
    collectionView.bounces = NO;
    collectionView.pagingEnabled = YES;
    collectionView.showsVerticalScrollIndicator = NO;
    collectionView.showsHorizontalScrollIndicator = NO;
    collectionView.backgroundColor = [UIColor clearColor];
    [collectionView registerNib:[UINib nibWithNibName:cellId bundle:nil] forCellWithReuseIdentifier:cellId];
    [self addSubview:collectionView];
    
    //
    UIPageControl *pageControl = [[UIPageControl alloc] init];
    pageControl.translatesAutoresizingMaskIntoConstraints = NO;
    [pageControl addConstraint:[NSLayoutConstraint constraintWithItem:pageControl attribute:NSLayoutAttributeWidth
                                                            relatedBy:NSLayoutRelationEqual
                                                               toItem:nil attribute:NSLayoutAttributeNotAnAttribute
                                                           multiplier:1 constant:self.bounds.size.width]];
    [pageControl addConstraint:[NSLayoutConstraint constraintWithItem:pageControl attribute:NSLayoutAttributeHeight
                                                            relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute
                                                           multiplier:1 constant:10]];
    
    [self addSubview:pageControl];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeBottom
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:pageControl attribute:NSLayoutAttributeBottom
                                                    multiplier:1 constant:10]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:pageControl attribute:NSLayoutAttributeCenterX
                                                         relatedBy:NSLayoutRelationEqual
                                                            toItem:self attribute:NSLayoutAttributeCenterX
                                                        multiplier:1 constant:0]];

    self.pageControl = pageControl;
    self.collectionView = collectionView;
}

- (void)willMoveToSuperview:(UIView *)newSuperview
{
    [super willMoveToSuperview:newSuperview];
    
    NSInteger count = [self.delegate numberOfImagesInBrowserView];
    NSInteger index = 0;
    if ([self.delegate respondsToSelector:@selector(indexForFirstShow)]) {
        index = [self.delegate indexForFirstShow];
    }
    self.pageControl.numberOfPages = count;
    self.pageControl.currentPage = index;
    self.collectionView.contentOffset = CGPointMake(index*self.bounds.size.width, 0);
}

- (void)closeBrowser:(UITapGestureRecognizer *)gestureRecognizer
{
    self.backgroundColor = [UIColor clearColor];
    
    UIImageView *imageView = [self.delegate viewOfBrowserViewRemoveToAtIndex:self.pageControl.currentPage];
    imageView.hidden = YES;
    
    WCNImageCCell *cell = [self.collectionView visibleCells][0];
    CGPoint point = cell.scrollView.contentOffset;
    CGRect frame = [imageView convertRect:imageView.bounds toView:self];
    frame.origin.x += point.x;
    frame.origin.y += point.y;
    
    [UIView animateWithDuration:.4 animations:^{
        cell.imageView.frame = frame;
    } completion:^(BOOL finished){
        imageView.hidden = NO;
        [self removeFromSuperview];
    }];
}

#pragma mark - Private

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [self.delegate numberOfImagesInBrowserView];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    WCNImageCCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
    cell.indexPath = indexPath;
    [(MBProgressHUD *)cell.hud hide:YES];
    
    NSString *stringId = [self.delegate browserItemIdForItemAtIndex:indexPath.row];
    WCImageType type = [self.delegate browserItemTypeForItemAtIndex:indexPath.row];
    UIImage *image = [[WCImageManager sharedMg] image:stringId type:type size:WCImageSizeBig cache:NO];
    if (image) {
        [cell setImage:image];
    } else {
        image = [[WCImageManager sharedMg] image:stringId type:type size:WCImageSizeSmall cache:YES];
        [cell setImage:image];
        
        //下载大图
        NSTimeInterval delay = .0;
        if (self.firstShow) {
            delay = .4;
        }
        [self performBlock:^{
            MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimpleInImageView:cell];
            cell.hud = hud;
            [[WCImageManager sharedMg] downloadImage:stringId type:type size:WCImageSizeBig cache:NO success:^(UIImage *image, NSString *stringId){
                [hud hide:YES];
                [cell setImage:image];
            } failure:^(NSError *error){
                [hud hide:YES];
            }];
        } afterDelay:delay];
    }
    
    if (self.firstShow) {
        self.firstShow = NO;
        
        UIImageView *imageView = [self.delegate viewOfBrowserViewshowFrom];
        CGRect frame = cell.imageView.frame;
        cell.imageView.frame = [imageView convertRect:imageView.bounds toView:self];
        [UIView animateWithDuration:.4 animations:^{
            cell.imageView.frame = frame;
        } completion:^(BOOL finished){ }];
    }
    
    return cell;
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //current page
    self.pageControl.currentPage = scrollView.contentOffset.x/self.bounds.size.width;
}

@end